package com.sdk.apiNotify.rabbitmq.consumber.handle;

import com.coment.dto.ApiNotify;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import com.sdk.apiNotify.rabbitmq.consumber.server.ApiNotifyPushService;
import com.sdk.apiNotify.rabbitmq.producer.ApiNotifyProducer;
import com.sdk.service.impl.ApiNotifyServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class ApiNotifyHandle implements ChannelAwareMessageListener {
   @Resource
   private ApiNotifyProducer apiNotifyProducer;
   @Resource
   private ApiNotifyPushService apiNotifyPushService;
   @Resource
   private ApiNotifyServiceImpl apiNotifyServiceImpl;

   public void onMessage(Message message, Channel channel) throws Exception {
      ObjectMapper mapper = new ObjectMapper();

      ApiNotify apiNotify;
      try {
         apiNotify = mapper.readValue(message.getBody(), ApiNotify.class);
      } catch (Exception e) {
         log.error("处理消息失败", e);
         throw new Exception("消息解析失败");
      }

      long deliveryTag = message.getMessageProperties().getDeliveryTag();

      try {
         this.apiNotifyPushService.handlerMessage(apiNotify);
         apiNotify.setStatus(1);
         this.apiNotifyServiceImpl.saveApiNotify(apiNotify);
         channel.basicAck(deliveryTag, false);
      } catch (Exception var8) {
         channel.basicNack(deliveryTag, false, false);
         apiNotify.setRetryCount(0);
         apiNotify.setStatus(0);
         this.apiNotifyProducer.sendToRetryQueue(apiNotify);
         this.apiNotifyServiceImpl.saveApiNotify(apiNotify);
      }

   }
}
